<?php

namespace app\common\api\controller;

use app\common\model\Member;
use app\common\model\MemberFinance;
use app\common\model\UcenterMember;
use think\Controller;
use app\common\api\controller\Bonus;
use think\Db;

class User extends Controller
{
    /**
     * 检测当前用户是否为管理员
     * @return boolean true-管理员，false-非管理员
     */
    public static function is_administrator($uid = null)
    {
        $uid = is_null($uid) ? is_login() : $uid;
        return $uid && (intval($uid) === C('USER_ADMINISTRATOR'));
    }

    /**
     * 根据用户ID获取用户名
     * @param integer $uid 用户ID
     * @return string       用户名
     */
    public static function get_username($uid = 0)
    {
        static $list;
        if (!($uid && is_numeric($uid))) { //获取当前登录用户名
            return session('user_auth.username');
        }

        /* 获取缓存数据 */
        if (empty($list)) {
            $list = S('sys_active_user_list');
        }

        /* 查找用户信息 */
        $key = "u{$uid}";
        if (isset($list[$key])) { //已缓存，直接使用
            $name = $list[$key];
        } else { //调用接口获取用户信息
            $User = new User\Api\UserApi();
            $info = $User->info($uid);
            if ($info && isset($info[1])) {
                $name = $list[$key] = $info[1];
                /* 缓存用户 */
                $count = count($list);
                $max = C('USER_MAX_CACHE');
                while ($count-- > $max) {
                    array_shift($list);
                }
                S('sys_active_user_list', $list);
            } else {
                $name = '';
            }
        }
        return $name;
    }

    /**
     * 更新会员资料
     * @param $uid
     * @param $userdata
     * @return bool
     */
    public function updateUser($uid, $userdata)
    {
        Db::startTrans();
        try {
            Db('member')->where('uid', $uid)->update($userdata);
            if (isset($userdata['usernumber'])) {
                Db('ucenter_member')->where('id', $uid)->setField('username', $userdata['usernumber']);
            }
            if (isset($userdata['mobile'])) {
                Db('ucenter_member')->where('id', $uid)->setField('mobile', $userdata['mobile']);
            }
            if (isset($userdata['email'])) {
                Db('ucenter_member')->where('id', $uid)->setField('email', $userdata['email']);
            }
            if (isset($userdata['psd1'])) {
                $password = think_ucenter_md5($userdata['psd1'], PASSWORD_KEY);
                Db('ucenter_member')->where('id', $uid)->setField('password', $password);
            }
            if (isset($userdata['psd2'])) {
                $password2 = think_ucenter_md5($userdata['psd2'], PASSWORD_KEY);
                Db('ucenter_member')->where('id', $uid)->setField('password2', $password2);
            }
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
    }

    /**
     * 会员注册
     * @param $data
     * @return int|string
     */
    public function register($data)
    {
        /*向ucenter_member数据表添加数据*/
        $ucenter_data['username'] = $data['usernumber'];
        $ucenter_data['password'] = $data['psd1'];
        $ucenter_data['password2'] = $data['psd2'];
        $ucenter_data['email'] = $data['email'];
        $ucenter_data['mobile'] = $data['mobile'];

        if ($data['mobile']) {
            $mobile = Db('member')->where('mobile', $data['mobile'])->find();
            if ($mobile) {
                return ['status' => 0, 'msg' => Error::regError(-11)];
            }
        }

        if ($data['email']) {
            $email = Db('member')->where('email', $data['email'])->find();
            if ($email) {
                return ['status' => 0, 'msg' => Error::regError(-8)];
            }
        }
        //数据验证
        $uvalidate = Validate('UcenterMember');
        $mvalidate = Validate('Member');
        if (!$mvalidate->check($data)) {
            return ['status' => 0, 'msg' => $mvalidate->getError()];
        }

        if (!$uvalidate->check($ucenter_data)) {
            return ['status' => 0, 'msg' => $uvalidate->getError()];
        }

        Db::startTrans();
        try {
            $member = new Member($data);
            $mret = $member->save();

            $uid = $member->uid;
            $ucenter_data['id'] = $uid;
            $ucenter = new UcenterMember($ucenter_data);
            $uret = $ucenter->save();

            $memberFinanceModel = new MemberFinance();
            $memberFinanceModel->uid = $uid;
            $memberFinanceModel->save();

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            return ['status' => 0, 'msg' => Error::regError(-500)];
        }

        return ['status' => 1, 'msg' => '注册成功', 'data' => $uid];
    }
}